package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Dsstorebill;
import cn.stylefeng.guns.sys.modular.system.entity.BtyInventory;
import cn.stylefeng.guns.sys.modular.system.service.BtyInventoryService;
import cn.stylefeng.guns.sys.modular.system.service.InventoryPriceService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("btyInventory")
public class BtyInventoryController {

    private static final String PREFIX = "/modular/system/btyInventory/";
    @Autowired
    private BtyInventoryService btyInventoryService;
    @Autowired
    private InventoryPriceService inventoryPriceService;

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping("")
    public String index() {
        return PREFIX + "btyInventory.html";
    }

    /**
     * @param timeLimit 时间范围
     * @param dm        店名
     * @param pl        品类
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String timeLimit, String dm, String pl) {
        String startTime ;
        String endTime ;
        //日期不为空
        if (StringUtils.isNotBlank(timeLimit)) {
            //当月第一天
            startTime = timeLimit.substring(0, 8) + "01";
            endTime = timeLimit.substring(13, 23);
        } else {
            SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");
            String time = sformat.format(new Date());
            StringBuilder sb = new StringBuilder(time);
            sb.replace(time.length()-2, time.length(), "01");
            startTime = sb.toString();
            endTime =time;

        }
        pl = "酱料";
        //查询
        List<Map<String, Object>> dataList = Lists.newLinkedList();
        Map<String, Object> dataMap = null;
        List<BtyInventory> list = this.btyInventoryService.selectData(dm, startTime, endTime, pl);

        for (int i = 0; i < list.size(); i++) {
            dataMap = Maps.newLinkedHashMap();
            dataMap.put("shopName", list.get(i).getShopName());
            //品类
            dataMap.put("pl", list.get(i).getPl());
            //项名
            dataMap.put("xm", list.get(i).getXm());
            //出库量或者入库量
            dataMap.put("result", convertNum(list.get(i).getResult()));
            //单位
            dataMap.put("unit", list.get(i).getUnit());
            //日期
            dataMap.put("date", timeLimit);
            //预警金额
            dataMap.put("printAmount",list.get(i).getPrice());
            dataList.add(dataMap);
        }
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(1, dataList.size(), dataList.size());
        page.setRecords(dataList);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 这才是最新版的展示数据
     * 返回所有的店名 当前店名包含的品类
     *
     * @return
     */
    @RequestMapping("/select_dm_pl")
    @ResponseBody
    private List<Map<String, List<String>>> selectDmAndPl() {
        List<Map<String, List<String>>> list = Lists.newLinkedList();
        Map<String, List<String>> map = null;
        List<String> listDm = this.btyInventoryService.select_dm();
        List<String> listPl = null;
        for (String dm : listDm) {
            map = Maps.newLinkedHashMap();
            listPl = Lists.newLinkedList();
            listPl = this.btyInventoryService.select_pl(dm);
            map.put(dm, listPl);
            list.add(map);
        }
        return list;
    }

    @RequestMapping("/select_dm")
    @ResponseBody
    private List<String> selectDmList() {
        List<String> list = this.btyInventoryService.select_dm();
        return list;
    }

    @RequestMapping("/selectPlForDm")
    @ResponseBody
    private List<String> selectPlforDm(String dm) {
        List<String> list = this.btyInventoryService.select_pl(dm);
        return list;
    }


    /**
     * 插入数据
     *
     * @param jsonArray
     */
    private void insertData(JSONArray jsonArray) {
        List<String> type = Lists.newLinkedList();
        type.add("门店统配入库");
        type.add("门店直配入库");
        type.add("门店自采入库");
        type.add("门店其他入库");
        type.add("门店期初单");
        type.add("店间调入");
        type.add("门店外销退货");
        type.add("门店冲减出库");
        type.add("门店报损出库");
        type.add("门店外销出库");
        type.add("门店统配退货单");
        type.add("门店部门领用");
        type.add("店内档口领用");
        type.add("店间调出");
        type.add("门店其他出库");
        type.add("门店自采退货");
        /**
         * ShopCode    ShopName	ItemSmallClassName  ItemName
         * 没有店名查询的的是所有的店,把获取到的数据取出来便利 然后挨个插入到表中
         */
        JSONObject jsonObject;
        List<BtyInventory> list = Lists.newLinkedList();
        for (int i = 0; i < jsonArray.size(); i++) {
            BtyInventory btyInventory = new BtyInventory();
            //把所有 ItemSmallClassName 为 酱料 的添加到list中
            jsonObject = jsonArray.getJSONObject(i);
            if ("酱料".equals(jsonObject.getOrDefault("ItemSmallClassName", "").toString())
                    && type.contains(jsonObject.getOrDefault("BillType", ""))
                    && !"山西配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())
                    && !"山东配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())) {
                //单据系统单号
                btyInventory.setBillNo(jsonObject.getOrDefault("BillNO", "").toString());

                //转换时间格式
                String date = convertTime(jsonObject.getOrDefault("MakeTime", "").toString());
                btyInventory.setScrq(date);
                //入库金额
                btyInventory.setRkje(convertNum(jsonObject.getOrDefault("InStoreMoney", "").toString()));
                btyInventory.setShopCode(jsonObject.getOrDefault("ShopCode", "").toString());
                btyInventory.setShopName(jsonObject.getOrDefault("ShopName", "").toString());
                btyInventory.setPl(jsonObject.getOrDefault("ItemSmallClassName", "").toString());
                btyInventory.setXm(jsonObject.getOrDefault("ItemName", "").toString());
                //判断长度是否大于4
                if (jsonObject.getOrDefault("InBusAmount", "").toString().length() > 4) {
                    //入库数量
                    btyInventory.setRk(convertNum(jsonObject.getOrDefault("InBusAmount", "").toString()));
                } else if (jsonObject.getOrDefault("OutBusAmount", "").toString().length() > 4) {
                    //出库数量
                    btyInventory.setCk(convertNum(jsonObject.getOrDefault("OutBusAmount", "").toString()));
                }
                btyInventory.setRq(convertTime(jsonObject.getOrDefault("busDate", "").toString()));
                //单据类型
                btyInventory.setType(jsonObject.getOrDefault("BillType", "").toString());

                btyInventory.setUnit(jsonObject.getOrDefault("ItemSpec", "").toString());
                list.add(btyInventory);
            }
        }
        //分批插入数据
        for (BtyInventory btyInventory : list) {
            int i = this.btyInventoryService.insertData(btyInventory);
        }

        System.out.println("插入insert1最终的条数：" + list.size());

    }

    /**
     * 插入数据
     *
     * @param jsonObject
     */
    private void insertData2(JSONObject jsonObject) {
        //需要统计库存的单据类型如下-BillType
        List<String> type = Lists.newLinkedList();
        type.add("门店统配入库");
        type.add("门店直配入库");
        type.add("门店自采入库");
        type.add("门店其他入库");
        type.add("门店期初单");
        type.add("店间调入");
        type.add("门店外销退货");
        type.add("门店冲减出库");
        type.add("门店报损出库");
        type.add("门店外销出库");
        type.add("门店统配退货单");
        type.add("门店部门领用");
        type.add("店内档口领用");
        type.add("店间调出");
        type.add("门店其他出库");
        type.add("门店自采退货");

        //数据转换
        List<Dsstorebill> dataArr = JSON.parseArray(jsonObject.getString("data"), Dsstorebill.class);

        List<BtyInventory> list = Lists.newLinkedList();
        //插入数据
        for (Dsstorebill btyInventory : dataArr) {


            if ("酱料".equals(btyInventory.getItemSmallClassName())
                    && type.contains(btyInventory.getBillType())
                    && !"山西配送中心".equals(btyInventory.getShopName())
                    && !"山东配送中心".equals(btyInventory.getShopName())) {


            }

        }


    }


    /**
     * 计算金额 = (手动输入的数量 - 库存数量) * 单价
     * 计算金额大于输入金额时，显示异常
     *
     * @param params
     * @return
     */

    @RequestMapping(value = "/selectMoney")
    @ResponseBody
    private Object selectMoney(BtyInventory params) {

        //构建查询参数
        String timeLimit = params.getDate();
        String startTime = timeLimit.substring(0, 8) + "01";
        String endTime = timeLimit.substring(13, 23);
        params.setStartTime(startTime);
        params.setEndTime(endTime);
        BtyInventory btyInventory = btyInventoryService.selectRkAndTotalRkje(params);
        BigDecimal unitPrice = BigDecimal.ZERO;
        //单价=入库金额/入库数量
        if (!"0".equals(btyInventory.getTotalRk())) {
            unitPrice = btyInventory.getTotalRkje().divide(btyInventory.getTotalRk(), 4, BigDecimal.ROUND_HALF_UP);
        }

        BigDecimal result = new BigDecimal(params.getSl()).subtract(new BigDecimal(params.getResult())).multiply(unitPrice);

        Boolean flag = false;
        //大于等于输入的金额
        if (result.compareTo(params.getPrintAmount()) == 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * 转换时间格式
     *
     * @param time 参数
     * @return 转换之后的时间格式
     */
    public static String convertTime(String time) {
        // May 31, 2020 1:43:39 PM
        Date date = new Date(time);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = simpleDateFormat.format(date);
        return time;
    }

    /**
     * 处理不合理数据，0E-8，0e-8
     */
    private String convertNum(String data) {
        if ("0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return "0";
        } else {
            return data;
        }
    }
}
